package com.naizhuai.ui.ainote;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;

import com.naizhuai.Model.db.ainote.Note;
import com.naizhuai.R;
import com.naizhuai.ui.BaseFragment;
import com.naizhuai.ui.adapter.ManageDividerItemDecoration;
import com.naizhuai.ui.ainote.note.NoteContract;
import com.naizhuai.ui.ainote.note.NotePresenter;
import com.naizhuai.ui.ainote.notesetting.AddDetialNoteActivity;
import com.naizhuai.ui.components.MultStateView;
import com.naizhuai.util.ConstantsParams;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * A simple {@link Fragment} subclass.
 */
public class StudyFragment extends BaseFragment implements NoteContract.View {
    int MENU_SORT_GROUP_ID = 11998811;
    public static final String KEY_CREATION = "creation";
    public static final String KEY_LAST_UPDATE = "last_update";
    public static final String KEY_TITLE = "title";
    private static final int NORMAL = 0;
    private static final int DELETE_NOTE = 1;
    private int status;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.contentRecycle)
    RecyclerView contentRecycle;
    @BindView(R.id.fab_add_task)
    FloatingActionButton fabAddNote;
    Unbinder unbinder;
    @BindView(R.id.stateView)
    MultStateView stateView;
    private NoteAdapter mNoteAdapter;
    private NoteContract.Presenter  mPresenter;
    private AppCompatActivity activity;

    public StudyFragment() {
        // Required empty public constructor
    }

    public static StudyFragment newInstance() {
        StudyFragment fragment = new StudyFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        activity = (AppCompatActivity) getActivity();
        activity.setSupportActionBar(toolbar);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_study, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        InitToolBar();
        InitFab();
        InitNoteList();
        InitPresenter();
    }

    private void InitPresenter() {
        mPresenter=new NotePresenter();
        String filter= getSp().getValue(ConstantsParams.PREF_SORTING_COLUMN,"");
        switch (filter){
            case KEY_CREATION:
                mPresenter.setFiltering(Note.NoteFilterType.CREATION);
                mNoteAdapter.setFilterType(Note.NoteFilterType.CREATION);
                break;
            case KEY_TITLE:
            case KEY_LAST_UPDATE:
            default:
                 mPresenter.setFiltering(Note.NoteFilterType.LAST_UPDATE);
                 mNoteAdapter.setFilterType(Note.NoteFilterType.LAST_UPDATE);
                 break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.takeView(this);
        fragmentBack();
    }

    private void fragmentBack() {
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
                if (status==DELETE_NOTE){
                    mNoteAdapter.clearSelected();
                    fabAddNote.show();
                    return true;
                }else {
                    return false;
                }
            }
            return false;
        });
    }

    private void InitNoteList() {
        mNoteAdapter=new NoteAdapter(getActivity());
        mNoteAdapter.getClickSubject().subscribe(note -> {
            Intent intent=new Intent(getActivity(),AddDetialNoteActivity.class);
            intent.putExtra(AddDetialNoteActivity.NOTE_DETIAL_ID,note.noteid);
            startActivity(intent);
        });
        mNoteAdapter.getSelectedClicks().subscribe(note -> updateToolbarFab());
        contentRecycle.setLayoutManager(new LinearLayoutManager(getActivity()));
        contentRecycle.addItemDecoration(new ManageDividerItemDecoration(getActivity(), ManageDividerItemDecoration.VERTICAL_LIST, 10, false));
        contentRecycle.setAdapter(mNoteAdapter);
    }

    private void updateToolbarFab() {
         if (editMode()){
             fabAddNote.hide();
             status=DELETE_NOTE;
             toolbar.setTitle(String.format(Locale.ENGLISH, "%d/%d",
                     mNoteAdapter.getSelectedCount(), mNoteAdapter.getItemCount()));
         }else{
             fabAddNote.show();
             status=NORMAL;
         }
        getActivity().invalidateOptionsMenu();
    }

    private void InitFab() {
        fabAddNote.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), AddDetialNoteActivity.class);
            startActivity(intent);
        });
    }



    private void InitToolBar() {

    }
    private void initSortingSubmenu(SubMenu sortMenu) {
        final String[] arrayDb = getResources().getStringArray(R.array.sortable_columns);
        final String[] arrayDialog = getResources().getStringArray(R.array.sortable_columns_human_readable);
        int selected = Arrays.asList(arrayDb).indexOf(getSp().getValue(ConstantsParams.PREF_SORTING_COLUMN, arrayDb[0]));
        for (int i = 0; i < arrayDialog.length; i++) {
            if (sortMenu.findItem(i) == null) {
                sortMenu.add(MENU_SORT_GROUP_ID, i, i, arrayDialog[i]);
            }
            if (i == selected) sortMenu.getItem(i).setChecked(true);
        }
        sortMenu.setGroupCheckable(MENU_SORT_GROUP_ID, true, true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
       if (editMode()){
           inflater.inflate(R.menu.menu_note_delete,menu);
           activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
       } else{
           inflater.inflate(R.menu.menu_filter,menu);
           activity.getSupportActionBar().setDisplayHomeAsUpEnabled(false);
           toolbar.setTitle(getString(R.string.ai_note));
       }
        super.onCreateOptionsMenu(menu, inflater);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.menu_sort:
                initSortingSubmenu(item.getSubMenu());
                break;
            case android.R.id.home:
                mNoteAdapter.clearSelected();
                break;
            case R.id.menu_all:
                if (mNoteAdapter.getSelectedCount()==mNoteAdapter.getItemCount()){
                    mNoteAdapter.clearSelected();
                }else {
                   mNoteAdapter.allSelected();
                }
                break;
            case R.id.menu_delete:
                ArrayList selectList=mNoteAdapter.getSelected();
                mPresenter.deleteNote(selectList);
                break;

        }

        if (item.getGroupId()==MENU_SORT_GROUP_ID){
            final String[] arrayDb = getResources().getStringArray(R.array.sortable_columns);
            getSp().saveValue(ConstantsParams.PREF_SORTING_COLUMN, arrayDb[item.getOrder()]);
            switch (arrayDb[item.getOrder()]){
                case KEY_TITLE:
                    mPresenter.setFiltering(Note.NoteFilterType.TITLE);
                    mNoteAdapter.setFilterType(Note.NoteFilterType.TITLE);
                    break;
                case KEY_CREATION:
                    mPresenter.setFiltering(Note.NoteFilterType.CREATION);
                    mNoteAdapter.setFilterType(Note.NoteFilterType.CREATION);
                    break;
                case KEY_LAST_UPDATE:
                    mPresenter.setFiltering(Note.NoteFilterType.LAST_UPDATE);
                    mNoteAdapter.setFilterType(Note.NoteFilterType.LAST_UPDATE);
                    break;
            }
           mPresenter.loadNotes();
        }

        return super.onOptionsItemSelected(item);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void showNotes(List<Note> notes) {
        stateView.showView(MultStateView.STATUS_CONTENT);
        mNoteAdapter.addNotes(notes);

    }

    @Override
    public void showNoTasks() {
        stateView.showView(MultStateView.STATUS_EMPTY);
    }

    @Override
    public void setLoadingIndicator() {
        stateView.showView(MultStateView.STATUS_LOADING);
    }

    @Override
    public void showSuccessfullySavedMessage() {

    }

    public boolean editMode() {
        return mNoteAdapter.selecting();
    }

    @Override
    public void showRecycleViewItem(List<Note> deletenote) {
        mNoteAdapter.removeSelect();
        fabAddNote.show();
        mNoteAdapter.clearSelected();


    }
}

